package com.shujia;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class QQTest {




    @Test
    public void client() throws Exception {
        Socket s = new Socket(InetAddress.getLocalHost(), 9999);
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter pw = new PrintWriter(s.getOutputStream());
        Scanner sc = new Scanner(System.in);
        while (true) {
            // client 发送数据
            String msg = sc.next();
            pw.println(msg);
            pw.flush();

            // 跳出循环
            if (msg.equals("exit")) {
                break;
            }

            // 接收server端响应数据
            String respMsg = br.readLine();
            System.out.println("服务端响应数据:" + respMsg);

        }

        br.close();
        pw.close();
        sc.close();
        s.close();
    }

    @Test
    public void server() throws Exception {
        ServerSocket ss = new ServerSocket(9999);
        Socket s = ss.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter pw = new PrintWriter(s.getOutputStream());
        Scanner sc = new Scanner(System.in);

        while (true) {
            // 读取数据
            String msg = br.readLine();
            System.out.println("接收到客户端消息:" + msg);

            if (msg.equals("exit")) {
                break;
            }

            // server端发送数据
            String respMsg = sc.next();
            pw.println(respMsg);
            pw.flush();
        }


        br.close();
        pw.close();
        sc.close();
        s.close();
    }
}